package Data;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import Domain.Book;
import Domain.BookList;
import Domain.Seller;
import Main.Constants;

/**
 * Mapper that loads data from the database into a {@link domain.BookList} object.
 * 
 * @author Johan Envik
 *
 */

public class BookListMapper {
	
	/**
	 * Searches for all the books in the database that matches the given
	 * search string. The result is returned as a {@link domain.BookList}
	 * object.
	 * 
	 * @param searchString
	 * 			the string used as search argument. Searches trough the title, author and isbn fields.
	 * 			The search is done based on substring and the case of letters are ignored.
	 * @return the {@link domain.BookList} object 
	 * 			containing all books that matches the search string.
	 * @throws SQLExceptionw
	 * 			if the database call fails.
	 * @throws ClassNotFoundException
	 * 			if the JDBC driver cannot be loaded.
	 */
	public BookList searchFor(String searchString) throws SQLException, ClassNotFoundException {
		BookList bookList = new BookList();

		Statement stmt = Database.createStatement();
		String selectString = Constants.FREE_SEARCH_BOOKS;
		selectString = selectString.replaceAll("::string", searchString);
		System.out.println("Calling database: " + selectString);
		ResultSet rs = stmt.executeQuery(selectString);
		
		while (rs.next()) {			
			SellerMapper sellerMapper = new SellerMapper();
			Seller seller = sellerMapper.retrieve(rs
					.getInt("seller_id_seller"));
			
			Book book = new Book(
					rs.getInt("id_book"),
					rs.getString("title"),
					rs.getString("isbn"),
					rs.getString("author"),
					rs.getString("edition"),
					rs.getString("condition"),
					rs.getString("subject"),
					rs.getDate("date_created"),
					rs.getInt("sold"),
					rs.getDouble("price"),
					seller);
		// System.out.println("Found product in database: " + product);
		bookList.addBook(book);
		}	
	// System.out.println("Return with" + productList.getProducts());
	return bookList;
	}
}
